package org.example.DAO;

import org.example.entity.BlogComment;
import org.example.DAO.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class BlogCommentDAO {
    private final Connection conn;

    public BlogCommentDAO(Connection conn) {
        this.conn = conn;
    }

    public boolean addComment(BlogComment comment) throws SQLException {
        String sql = "INSERT INTO BlogComment (COMMENTID, BLOGID, USERID, CONTENT, CREATED_AT, PARENTID, USERNAME, AVATAR) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, UUID.randomUUID().toString());
            stmt.setString(2, comment.getBlogId());
            stmt.setInt(3, comment.getUserId());
            stmt.setString(4, comment.getContent());
            stmt.setTimestamp(5, new java.sql.Timestamp(new Date().getTime()));
            // 处理parentId为null的情况
            if (comment.getParentId() != null && !comment.getParentId().isEmpty()) {
                stmt.setString(6, comment.getParentId());
            } else {
                stmt.setNull(6, java.sql.Types.VARCHAR);
            }
            stmt.setString(7, comment.getUsername());
            stmt.setString(8, comment.getAvatar());
            return stmt.executeUpdate() > 0;
        }
    }

    public List<BlogComment> getCommentsByBlogId(String blogId) throws SQLException {
        List<BlogComment> comments = new ArrayList<>();
        String sql = "SELECT * FROM BlogComment WHERE BLOGID = ? ORDER BY CREATED_AT DESC";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, blogId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                BlogComment comment = new BlogComment();
                comment.setCommentId(rs.getString("COMMENTID"));
                comment.setBlogId(rs.getString("BLOGID"));
                comment.setUserId(rs.getInt("USERID"));
                comment.setContent(rs.getString("CONTENT"));
                comment.setCreatedAt(rs.getTimestamp("CREATED_AT"));
                comment.setParentId(rs.getString("PARENTID"));
                comment.setUsername(rs.getString("USERNAME"));
                comment.setAvatar(rs.getString("AVATAR"));
                comments.add(comment);
            }
        }
        return comments;
    }
}